package com.lagou.edu.linstener;

import com.lagou.edu.pojo.Order;
import com.lagou.edu.service.OrderService;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;


@Component
public class OrderTimeOutLisenter {

	private final OrderService orderService;

	public OrderTimeOutLisenter(OrderService orderService) {
		this.orderService = orderService;
	}

	@RabbitListener(queues = "q.pay.dlx")
	public void onMessage(Message message, Channel channel) throws IOException {

		String str = new String(message.getBody(), message.getMessageProperties().getContentEncoding());
		System.out.println("处理订单：" + str);

		Order order = orderService.selectOrderByOrderId(str);
		if (order==null){
			System.out.println("无法找到订单");
		}else{
			if (order.getState() == 1) {
				System.out.println("失效订单号：" + str);
				orderService.updateOrder(order.getOrderId(),3);
				System.out.println("已经更新为失效订单");
			}
		}
		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	}
}
